package com.js.rtu.fragment.first;

import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.js.rtu.R;
import com.js.rtu.RTUApplication;
import com.js.rtu.adapter.DeviceAdapter;
import com.js.rtu.adapter.DeviceBean;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.event.onConnectionStateChangedEvent;
import com.js.rtu.util.SPUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import cn.wandersnail.bluetooth.BTManager;
import cn.wandersnail.bluetooth.ConnectCallback;
import cn.wandersnail.bluetooth.Connection;
import cn.wandersnail.bluetooth.DiscoveryListener;
import cn.wandersnail.bluetooth.EventObserver;


/**
 * 蓝牙连接
 */
public class BleListFragment extends BaseFragment implements EventObserver {


    @BindView(R.id.rcy_list)
    RecyclerView rcyList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private DeviceAdapter mAdapter;
    private List<String> macList;
    private String fitterStr="";//筛选条件
    private  DeviceBean curBean;//当前连接的Ble
    public static BleListFragment newInstance() {
        Bundle args = new Bundle();
        BleListFragment fragment = new BleListFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_first_blelist;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        macList = new ArrayList<>();
        mAdapter = new DeviceAdapter(_mActivity, null);
        initRecyclerView(rcyList, mAdapter, 1);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                fitterStr = (String) SPUtils.get(_mActivity, "fitter", "");
                macList.clear();
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
                if (BTManager.getInstance().isDiscovering())
                    BTManager.getInstance().stopDiscovery();
                if (BTManager.getInstance().isBluetoothOn())
                    BTManager.getInstance().startDiscovery();
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (adapter.getData().size() == 0)
                    return;
                DeviceBean bean = (DeviceBean) adapter.getData().get(position);
                if (bean != null&& connection==null) {
                    //连接
                    connect(bean);
                }
//                    EventBus.getDefault().post(new StartBrotherEvent(ConnectFragment.newInstance(bean)));


            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //断开连接
                  DeviceBean bean = (DeviceBean)  adapter.getData().get(position);
                if (connection!=null&&bean != null&&bean.isConntect()&&connection.isConnected()) {
                    bean.setConntect(false);
                    connection.disconnect();
                    connection=null;
                    mAdapter.notifyDataSetChanged();
                }

            }
        });

        BTManager.getInstance().addDiscoveryListener(discoveryListener);
        refreshLayout.autoRefresh();
    }




    private DiscoveryListener discoveryListener = new DiscoveryListener() {
        @Override
        public void onDiscoveryStart() {
            //搜索开始
            macList.clear();
            mAdapter.getData().clear();
            if (curBean!=null&&connection.isConnected())
            mAdapter.addData(curBean);

        }

        @Override
        public void onDiscoveryStop() {
            //搜索停止
            refreshLayout.finishRefresh();
        }

        /**
         * 搜索到蓝牙设备
         *
         * @param device 搜索到的设备
         * @param rssi   信号强度
         */
        @Override
        public void onDeviceFound(BluetoothDevice device, int rssi) {
            //搜索结果
            if (device.getName()!=null)
            if (!macList.contains(device.getAddress())) {
//                if (device.getAddress().contains(fitterStr) ||
                if (fitterStr.isEmpty()) {
                        mAdapter.addData(new DeviceBean(device, rssi));
                        mAdapter.notifyDataSetChanged();
                        macList.add(device.getAddress());
                } else {
                    if (device.getName() != null) {
                        if (device.getName().toLowerCase().contains(fitterStr.toLowerCase())) {
                            mAdapter.addData(new DeviceBean(device, rssi));
                            mAdapter.notifyDataSetChanged();
                            macList.add(device.getAddress());
                        }
                    }


                }

            }


        }

        @Override
        public void onDiscoveryError(int errorCode, String errorMsg) {
            toastShow(errorMsg);
//            switch (errorCode) {
//                case DiscoveryListener.ERROR_LACK_LOCATION_PERMISSION://缺少定位权限
//                    toastShow("缺少定位权限");
//                    break;
//                case DiscoveryListener.ERROR_LOCATION_SERVICE_CLOSED://位置服务未开启
//                    toastShow("系统位置服务未开启");
//                    break;
//                case DiscoveryListener.ERROR_SCAN_FAILED://搜索失败
//                    toastShow("搜索错误");
//                    break;
//            }
        }
    };


    @Override
    public void onPause() {
        super.onPause();
        if (BTManager.getInstance().isInitialized()) {
            BTManager.getInstance().stopDiscovery();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        BTManager.getInstance().removeDiscoveryListener(discoveryListener);
        EventBus.getDefault().unregister(this);
    }

    private Connection connection;
    public void connect(DeviceBean bean) {
        UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        BluetoothDevice beanDevice = bean.getDevice();
         connection= RTUApplication.getInstance().getConnection(beanDevice);
        if (connection == null){
            toastShow("连接失败，找不到设备");
            return;
        }

        if (connection.isConnected()) {
            toastShow("已连接");
            return;
        }
        showLoadingDialog("正在连接");
        connection.connect(SPP_UUID, new ConnectCallback() {
            @Override
            public void onSuccess() {
                _mActivity. runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        bean.setConntect(true);
                        mAdapter.notifyDataSetChanged();
                        curBean=bean;
                    }

                });

            }

            @Override
            public void onFail(@NonNull String errMsg, @Nullable Throwable e) {
                _mActivity. runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showLoadingDialog("连接失败");
                        dismissLoadingDialog();
                        bean.setConntect(false);
                        mAdapter.notifyDataSetChanged();
                    }

                });
//                RTUApplication.getInstance().releaseConnection();
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConnectionStateChangedEvent(onConnectionStateChangedEvent event) {


        switch (event.getState()) {
            case Connection.STATE_CONNECTED:
                break;
            case Connection.STATE_DISCONNECTED:
            case Connection.STATE_RELEASED:
                curBean=null;
                connection=null;
//                EventBus.getDefault().post("连接已断开");
                refreshLayout.autoRefresh(400);
                break;
            default:
                break;
        }


    }
}
